<!--富文本-->
<template>
    <div style="height: 100%">
        <mavon-editor style="height: 600px" ref=md v-model="context" :toolbars="toolbars" @imgAdd="$imgAdd" @imgDel="$imgDel" v-if="!isText">
        </mavon-editor>

        <div id="RichText" v-show="isText">
        </div>
        <div style="height: 20px;">

            <el-button type="primary" @click="getRichTextHtml">确 定</el-button>
            <el-button
                :title="isText?'切换MarkDown格式':'切换富文本格式'"
                @click="isText = !isText"
                class="el-icon-refresh"
            ></el-button>
        </div>
    </div>
</template>

<script>
import E from "wangeditor"
import {computeFileHash} from "@/utils/fileUtil";

//https://hinesboy.github.io/mavonEditor/
import 'mavon-editor/dist/css/index.css'

export default {
    name: "richText",
    data() {
        return {
            //富文本框
            editor: null,
            //切换文本框
            isText: false,
            //api
            api: this.$store.getters.app.api,
            //用户信息
            userInfo: this.$store.getters.app.userInfo,
            //上传的文件id
            uploadFileId: [],
            //上传的文件id md
            uploadFileIdMd: [],
            //markdown字段
            context: ' ',//输入的数据,
            toolbars: {
                bold: true, // 粗体
                italic: true, // 斜体
                header: true, // 标题
                underline: true, // 下划线
                strikethrough: true, // 中划线
                mark: true, // 标记
                superscript: true, // 上角标
                subscript: true, // 下角标
                quote: true, // 引用
                ol: true, // 有序列表
                ul: true, // 无序列表
                link: true, // 链接
                imagelink: true, // 图片链接
                code: true, // code
                table: true, // 表格
                fullscreen: true, // 全屏编辑
                readmodel: true, // 沉浸式阅读
                htmlcode: true, // 展示html源码
                help: false, // 帮助
                /* 1.3.5 */
                undo: false, // 上一步
                redo: false, // 下一步
                trash: false, // 清空
                save: false, // 保存（触发events中的save事件）
                /* 1.4.2 */
                navigation: true, // 导航目录
                /* 2.1.8 */
                alignleft: true, // 左对齐
                aligncenter: true, // 居中
                alignright: true, // 右对齐
                /* 2.2.1 */
                subfield: true, // 单双栏模式
                preview: true, // 预览
            }
        }
    },
    async mounted() {
        await this.createRichText();
    },
    methods: {
        /**
         * markdown 上串图片
         * @param pos
         * @param $file
         * @returns {Promise<void>}
         */
        async $imgAdd(pos, $file) {
            const formData = new FormData();
            let hashValue = await computeFileHash($file);
            formData.append('hashValues', hashValue)
            formData.append("files", $file);
            console.log(formData);
            //调用接口
            this.api.user.upload(formData).then(res => {
                if (res.code === 200) {
                    for (let i = 0; i < res.data.length; i++) {
                        this.$refs.md.$img2Url(pos, res.data[i].url)
                        this.uploadFileIdMd.push(res.data[i].id)
                        console.log(this.uploadFileIdMd, "this.uploadFileId")
                    }
                }
            })
        },
        $imgDel(pos) {
            console.log(pos, "pos")
            this.uploadFileIdMd.splice(pos[0], 1)
            console.log(this.uploadFileIdMd, "this.uploadFileId")
            delete this.img_file[pos];
        },
        //创建富文本
        async createRichText() {
            this.editor = new E('#RichText')
            this.editor.config.height = 500;
            this.editor.config.menus = [
                'head',          //标题
                'bold',          //加粗
                'fontSize',         //字号
                'fontName',         //字体
                'italic',           //斜体
                'underline',        //下划线
                'strikeThrough',    //删除线
                'indent',           //缩进
                'lineHeight',       //行高
                'foreColor',        //文字颜色
                'backColor',        //背景色
                'link',             //连接
                'list',             //序列
                'todo',             //待办事项
                'justify',          //对其
                'quote',            //引用
                'emoticon',         //表情
                'image',            //图片
                'video',            //视频
                'table',            //表格
                'code',             //代码
                'splitLine',        //分割线
                'undo',             //撤销与回退
                'redo',             //全屏
            ]
            await this.RichTextFileUpload(this.editor)
            this.editor.create()
        },
        //新增文章
        getRichTextHtml() {
            let html = null;
            if (this.isText) {
                html = this.editor.txt.html()
            } else {
                html = this.$refs.md.d_render
            }
            if (html) {
                let data = {
                    userid: this.userInfo.username,
                    content: html,
                    fileIds: this.uploadFileId
                }
                this.api.article.insertArticle(data).then(res => {
                    if (res.code == 200) {
                        this.$message("新增成功！")
                    }
                })
            }
        },
        //图片上传
        async RichTextFileUpload() {
            let that = this;
            this.editor.config.customUploadImg = async function (resultFiles, insertImgFn) {
                //配置参数
                //console.log(resultFiles)
                const formData = new FormData()
                for (let i = 0; i < resultFiles.length; i++) {
                    let file = resultFiles[i];
                    let hashValue = await computeFileHash(file);
                    formData.append('hashValues', hashValue)
                    //console.log("dddd",file,hashValue)
                    formData.append('files', file)
                }
                //调用接口
                that.api.user.upload(formData).then(res => {
                    if (res.code === 200) {
                        for (let i = 0; i < res.data.length; i++) {
                            // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
                            insertImgFn(res.data[i].url)

                            that.uploadFileId.push(res.data[i].id)
                        }

                    }
                })
            }
        }
    }
}
</script>

<style scoped>
.el-button {
    margin: 10px 0px 10px 10px;
    float: right;
}

.w-e-full-screen-editor {
    top: 0;
}
</style>
